package com.example.system.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.R;
import com.example.system.entity.Department;
import com.example.system.entity.Doctor;
import com.example.system.mapper.DepartmentMapper;
import com.example.system.mapper.DoctorMapper;
import com.example.system.service.IDepartmentService;
import com.example.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 王鹤蒲
 * @since 2024-01-21
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private IUserService iUserService;

    @Override
    public R selectAll(String name) {
        LambdaQueryWrapper<Department> departmentLambdaQueryWrapper=new LambdaQueryWrapper<>();
        departmentLambdaQueryWrapper.eq(Department::getDelFlag,'0');
        List<Department> firstClassDepartmentList=new ArrayList<>();
        if("".equals(name)){
        List<Department> departmentList=departmentMapper.selectList(departmentLambdaQueryWrapper);
        firstClassDepartmentList=departmentList.stream().filter(department -> department.getParentId()==null).sorted(Comparator.comparing(Department::getSortNum)).collect(Collectors.toList());
        for(Department firstClassDepartment:firstClassDepartmentList){
         Integer parentId=firstClassDepartment.getId();
         List<Department> secondClassDepartmentList=departmentList.stream().filter(secondClassDepartment->parentId.equals(secondClassDepartment.getParentId())).sorted(Comparator.comparing(Department::getSortNum)).collect(Collectors.toList());
         firstClassDepartment.setSecondClassDepartmentList(secondClassDepartmentList);
        }
       }else {
            departmentLambdaQueryWrapper.eq(StrUtil.isNotBlank(name), Department::getName, name);
            Department department = departmentMapper.selectOne(departmentLambdaQueryWrapper);
            if (department.getParentId() == null) {
                departmentLambdaQueryWrapper.clear();
                departmentLambdaQueryWrapper.eq(Department::getDelFlag, '0');
                departmentLambdaQueryWrapper.eq(Department::getParentId, department.getId());
                departmentLambdaQueryWrapper.orderByAsc(Department::getSortNum);
                List<Department> secondClassDepartmentList = departmentMapper.selectList(departmentLambdaQueryWrapper).stream().sorted(Comparator.comparing(Department::getSortNum)).collect(Collectors.toList());
                department.setSecondClassDepartmentList(secondClassDepartmentList);
                firstClassDepartmentList.add(department);
            } else {
                departmentLambdaQueryWrapper.clear();
                departmentLambdaQueryWrapper.eq(Department::getDelFlag, '0');
                departmentLambdaQueryWrapper.eq(Department::getId, department.getParentId());
                Department firstClassDepartment = departmentMapper.selectOne(departmentLambdaQueryWrapper);
                List<Department> secondClassDepartmentList = new ArrayList<>();
                secondClassDepartmentList.add(department);
                firstClassDepartment.setSecondClassDepartmentList(secondClassDepartmentList);
                firstClassDepartmentList.add(firstClassDepartment);
            }
        }
        return R.success(firstClassDepartmentList);
    }

    @Override
    public R insert(Department department) {
        LocalDateTime createTime=LocalDateTime.now();
        department.setCreateBy(iUserService.getCurrentLoginUser().getUserName()).setCreateTime(createTime);
        departmentMapper.insert(department);
        return R.success();
    }

    @Override
    public R deleteById(Integer id) {
        LocalDateTime deleteTime=LocalDateTime.now();
        LambdaUpdateWrapper<Department> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        LambdaQueryWrapper<Department> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaUpdateWrapper.set(Department::getDelFlag,"1");
        lambdaUpdateWrapper.set(Department::getStatus,"0");
        lambdaUpdateWrapper.set(Department::getUpdateBy,iUserService.getCurrentLoginUser().getUserName());
        lambdaUpdateWrapper.set(Department::getUpdateTime,deleteTime);
        lambdaUpdateWrapper.eq(Department::getId,id);
        lambdaQueryWrapper.eq(Department::getId,id);
        lambdaUpdateWrapper.or(departmentMapper.selectOne(lambdaQueryWrapper).getParentId()==null,i->i.eq(Department::getParentId,id));
        departmentMapper.update(new Department(),lambdaUpdateWrapper);
        return R.success();
    }

    @Override
    public R deleteByIds(Integer[] ids) {
        LocalDateTime deleteTime=LocalDateTime.now();
       for(Integer id:ids){
           LambdaUpdateWrapper<Department> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
           LambdaQueryWrapper<Department> lambdaQueryWrapper=new LambdaQueryWrapper<>();
           lambdaUpdateWrapper.set(Department::getDelFlag,"1");
           lambdaUpdateWrapper.set(Department::getStatus,"0");
           lambdaUpdateWrapper.set(Department::getUpdateBy,iUserService.getCurrentLoginUser().getUserName());
           lambdaUpdateWrapper.set(Department::getUpdateTime,deleteTime);
           lambdaUpdateWrapper.eq(Department::getId,id);
           lambdaQueryWrapper.eq(Department::getId,id);
           lambdaUpdateWrapper.or(departmentMapper.selectOne(lambdaQueryWrapper).getParentId()==null,i->i.eq(Department::getParentId,id));
           departmentMapper.update(new Department(),lambdaUpdateWrapper);
       }
        return R.success();
    }

    @Override
    public R edit(Department department) {
        LocalDateTime updateTime=LocalDateTime.now();
        department.setUpdateBy(iUserService.getCurrentLoginUser().getUserName()).setUpdateTime(updateTime);
        departmentMapper.updateById(department);
        return R.success();
    }

    @Override
    public R findAll() {
        return R.success(departmentMapper.findAll());
    }

    @Override
    public R selectSecondClassDepartmentInfosList() {
        LambdaQueryWrapper<Department> departmentLambdaQueryWrapper=new LambdaQueryWrapper<>();
        departmentLambdaQueryWrapper.eq(Department::getStatus,"1");
        departmentLambdaQueryWrapper.eq(Department::getDelFlag,"0");
        departmentLambdaQueryWrapper.isNotNull(Department::getParentId);
        List<Department> secondClassDepartmentList=departmentMapper.selectList(departmentLambdaQueryWrapper);
        secondClassDepartmentList.forEach(department -> {
            List<Doctor> doctorList=doctorMapper.findAllByDepartmentId(department.getId());
            department.setDoctorList(doctorList);
        });
        return R.success(secondClassDepartmentList);
    }

    @Override
    public R selectDepartmentInfoById(Integer departmentId) {
        Department department=departmentMapper.selectById(departmentId);
        return R.success(department);
    }


}
